<template>
	<view class="map">
		<map id="map" :longitude="longitude" :latitude="latitude" :scale="scale" :markers="markers"
			:show-location="true" ref="map" class="vh_map" :enable-3D="true" :enable-poi="true" @markertap="markertap"
			@callouttap.stop="callouttap" :customCallout="callout">
		</map>
		<scroll-view scroll-x="true" class="kite-classify-scroll" id="myScrollView" :scroll-left="scrollLeft"
			@scroll="scroll" :scroll-with-animation="true" :show-scrollbar="false" enable-flex
			:scroll-into-view="toView">
			<view class="flex-container">
				<view v-for="(item,index) in mapList" :key="index" :id="'item-' + item.shop_id"
					class="kite-classify-comlun">
					<view class="flex_box">
						<view class="header_deatil"
							@click.stop="$ROUTELINK('/pageA/shop/particulars?shop_id=' + item.shop_id)">
							<image :src="item.image" mode="aspectFill" class="img"></image>
							<view class="right_comlumn">
								<!-- 店铺名称 -->
								<view class="header_title">
									<image :src="item.category_image" mode="aspectFill" class="darg"
										v-if="item.category_image"></image>
									<view class="title">
										{{ item.name }}
									
									</view>
								</view>
								<!-- 营业时间 -->
								<view class="business_hours">
									<view class="business_left">
										<view class="official"
											:style="{color:(item.manage == 1 ?'#81CAC5':item.manage == 2 ?'#B6B6B6':'#EAAF3B')}">
											{{item.manage_str}}
										</view>

										<view class="concrete_time">
											{{item.manage_time}}
										</view>
										<view class="size1">
											{{item.label}}
										</view>
									</view>
									<view class="navigation">
										<image :src="$IMG_URL('/static/home/navigation.png')" mode="" class="logo">
										</image>
										<view class="size">
											{{item.distance}}
										</view>
									</view>
								</view>
								<!-- 地址 -->
								<view class="address">
									{{ item.address }}
								</view>
							</view>
						</view>
						<view class="foot_box">
							<view class="btn1" @click.stop="ArrivalGuide(item, index)">
								到店指引
							</view>
							<view class="btn2" @click.stop="navigation(item, index)">
								导航
							</view>
						</view>
					</view>
				</view>
				<view class="holder_box">

				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		props: {
			mapList: {
				type: Array,
				default: [],
				required: true
			},
			latitude: {
				type: Number,
				default: 0,
				required: true
			},
			longitude: {
				type: Number,
				default: 0,
				required: true
			},
			scale: {
				type: Number,
				default: 10,
				required: true
			},
			mapShow: {
				type: Boolean,
				default: true,
				required: true
			},
		},
		data() {
			return {
				// 地图坐标
				// latitude: 27.969428, // 纬度
				// longitude: 120.615206, // 经度
				// scale: 15, // 缩放级别
				// 地图列表
				clusterMarkers: [],
				markers: [],
				// getLabelById: null,
				itemWidth: 674, // 每个滚动列表项的宽度
				scrollLeft: 0, // 初始滚动位置
				centeredItemIndex: 0,
				currentScrollLeft: 0,
				toView: '',
				localScale: this.scale, // 初始值为 props 的值
				currentLatitude: null, // 当前地图中心纬度
				currentLongitude: null, // 当前地图中心经度
			}
		},
		onReady() {
			this._mapContext = uni.createMapContext("map", this);
			this.cluster()
			this.getLabelById = this.mapList[0].shop_id
			this.toView = 'item-' + this.mapList[0].shop_id
			console.log('this.getLabelById', this.getLabelById);
			this.activeMarkers()
			console.log('onReady');

		},
		mounted() {

		},
		methods: {
			updateMapCenter(latitude, longitude) {
				// 避免重复更新相同坐标，减少闪动
				if (this.currentLatitude === latitude && this.currentLongitude === longitude) {
					return;
				}
				
				this.currentLatitude = latitude;
				this.currentLongitude = longitude;
				
				this._mapContext.moveToLocation({
					latitude: Number(latitude),
					longitude: Number(longitude),
					complete: (res) => {
						console.log('地图中心位置更新成功', res);
					}
				});
				
				// 适当调整缩放级别
				if (this.localScale < 15) {
					this.localScale = 15;
				}
			},
			scroll(e) {
				// 使用更短的节流时间，减少滚动闪动
				this.$u.throttle(() => {
					// 每个item的实际宽度：652rpx + 22rpx(margin-left) = 674rpx = 337px
					const itemWidth = 337;
					const scrollLeft = e.detail.scrollLeft;
					
					console.log('scrollLeft:', scrollLeft);
					
					// 检查 mapList 是否为空
					if (!this.mapList || this.mapList.length === 0) {
						console.error('mapList is empty or not loaded yet:', this.mapList);
						return;
					}
					
					// 计算当前应该显示的索引，考虑第一个item的偏移
					let currentIndex = Math.round((scrollLeft + itemWidth / 2) / itemWidth);
					
					// 确保索引在有效范围内
					currentIndex = Math.max(0, Math.min(currentIndex, this.mapList.length - 1));
					
					console.log('currentIndex:', currentIndex);
					
					// 获取当前选中的店铺
					const item = this.mapList[currentIndex];
					if (!item || !item.shop_id) {
						console.error('Invalid item at currentIndex:', currentIndex, item);
						return;
					}
					
					// 如果选中的店铺发生了变化，才更新地图和标记
					if (this.getLabelById !== item.shop_id) {
						// 更新地图中心位置
						this.updateMapCenter(item.lat, item.long);
						
						// 更新当前选中的店铺
						this.getLabelById = item.shop_id;
						this.activeMarkers();
					}
				}, 200); 
			},
			// 导航
			navigation(item, index) {
				console.log('item', item);
				let that = this
				uni.openLocation({
					latitude: Number(item.lat), //要去的纬度-地址
					longitude: Number(item.long), //要去的经度-地址
					address: item.address, //要去的具体地址
				})
			},
			// 到店指引
			ArrivalGuide(item, index) {
				console.log('item', item);
				uni.navigateTo({
					url: '/pageA/shop/Arrival-guide?shop_id=' + item.shop_id
				})
			},
			// 点聚合
			cluster() {
				this._mapContext.initMarkerCluster({
					enableDefaultStyle: false, // 是否使用默认样式
					zoomOnClick: true, // 点击聚合的点，是否改变地图的缩放级别
					gridSize: 60, // 聚合计算时网格的像素大小，默认60
					complete(res) {
						console.log('initMarkerCluster', res)
					}
				});

				this._mapContext.on("markerClusterCreate", (res) => {
					console.log("markerClusterCreate", res);
					const clusters = res.clusters
					const that = this
					this.clusterMarkers = clusters.map(cluster => {
						const {
							center,
							clusterId,
							markerIds
						} = cluster
						console.log('cluster', cluster);
						return {
							...center,
							width: 0,
							height: 0,
							clusterId, // 必须
							iconPath: that.$IMG_URL('/static/coach/blank.png'),
							label: {
								content: markerIds.length + '',
								fontSize: 16,
								color: '#ffffff',
								width: 50,
								height: 50,
								bgColor: "#81CAC5",
								borderRadius: 25,
								textAlign: 'center',
								anchorX: 0,
								anchorY: -20,
							}
						}
					})
					this._mapContext.addMarkers({
						markers: this.clusterMarkers,
						clear: false,
						complete(res) {
							console.log('clusterCreate addMarkers', res)
						}
					})
				});
				this._mapContext.on('markerClusterClick', (res) => {
					console.log('markerClusterClick', res)
					if (typeof res.cluster === 'object') {
						console.log('object');
					}
				})
				this.addMarkers();

			},
			addMarkers() {
				const positions = []
				this.mapList.forEach(i => {
					positions.push({
						latitude: i.lat,
						longitude: i.long,
						title: i.name,
						id: i.shop_id
					})
				})
				console.log('positions', positions);

				positions.forEach((p, i) => {
					this.markers.push(
						Object.assign({}, {
							id: p.id,
							iconPath: this.$IMG_URL('/static/coach/map_icon.png'),
							width: 24,
							height: 24,
							joinCluster: true, // 指定了该参数才会参与聚合
							callout: {
								bgColor: "#ffffff",
								color: "#333333",
								content: `${p.title}`,
								display: "ALWAYS",
								fontSize: "14",
								fontWeight: "bold",
								padding: 8,
								textAlign: "center"
							}
						}, p)
					)
				})
				this._mapContext.addMarkers({
					markers: this.markers,
					clear: false,
					complete(res) {
						console.log('addMarkers', res)
					}
				})
			},
			markertap(message) {
				console.log('message', message);
			},
			activeMarkers() {
				console.log('activeMarkers');
				this.markers = this.markers.map(marker => ({
					...marker,
					callout: {
						...marker.callout,
						bgColor: marker.id === this.getLabelById ? '#81CAC5' : '#ffffff',
						color: marker.id === this.getLabelById ? '#ffffff' : '#333333'
					}
				}));
			},
			callouttap(message) {
				console.log('callouttap message', message);
				const markerId = message.detail.markerId;
				this.getLabelById = markerId;
				
				// 找到对应的店铺在列表中的索引
				const targetIndex = this.mapList.findIndex(item => item.shop_id === markerId);
				console.log('targetIndex:', targetIndex);
				
				if (targetIndex !== -1) {
					// 计算应该滚动到的位置，每个item宽度337px，加上margin
					const itemWidth = 337;
					const targetScrollLeft = targetIndex * itemWidth;
					
					// 设置滚动位置和目标视图
					this.scrollLeft = targetScrollLeft;
					this.toView = 'item-' + markerId;
					
					console.log('scrolling to position:', targetScrollLeft);
				}
				
				this.activeMarkers();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.holder_box {
		width: 652rpx;
		height: 300rpx;
		border-radius: 16rpx;
		box-shadow: 0rpx 30rpx 40rpx 0rpx rgba(193, 193, 193, 0.16);
		margin-left: 22rpx;
		display: inline-block;
	}

	.customCallout {
		background: #FFFFFF;
		box-shadow: 0px 8rpx 32rpx 0px rgba(189, 191, 193, 0.4);
		border-radius: 10rpx;
		padding: 6rpx 24rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		box-sizing: border-box;

		.content-image {
			width: 60rpx;
			height: 60rpx;
			margin-left: 10rpx;
		}

		.txt {
			font-size: 32rpx;
		}
	}

	.map {


		.vh_map {
			width: 100%;
			height: 80vh;
		}

		.kite-classify-scroll {
			position: fixed;
			bottom: 28rpx;
			width: 100%;
			overflow: hidden;
			white-space: nowrap;

			.flex-container {
				width: 100%;
				display: flex;
				flex-direction: row;
				align-items: center;

			}

			.kite-classify-comlun {
				display: inline-block;
				width: 652rpx;
				height: 300rpx;
				background: #ffffff;
				border-radius: 16rpx;
				box-shadow: 0rpx 30rpx 40rpx 0rpx rgba(193, 193, 193, 0.16);
				margin-left: 22rpx;

				.flex_box {
					display: flex;
					flex-direction: column;
					width: 100%;
					height: 100%;
					padding: 20rpx;

					.header_deatil {
						display: flex;
						flex-direction: row;
						width: 100%;
						margin-bottom: 24rpx;

						.img {
							width: 164rpx;
							height: 164rpx;
							border-radius: 16rpx;
							margin-right: 16rpx;
						}

						.right_comlumn {
							width: 432rpx;
							display: flex;
							flex-direction: column;

							.header_title {
								display: flex;
								flex-direction: row;
								align-items: center;
								margin-bottom: 6rpx;

								.darg {
									width: 114rpx;
									height: 36rpx;
									margin-right: 8rpx;
								}

								.title {
									font-size: 32rpx;
									font-family: PingFang SC, PingFang SC-Bold;
									font-weight: 700;
									text-align: left;
									color: #333333;
									overflow: hidden;
									text-overflow: ellipsis;
									white-space: nowrap
								}
							}

							.business_hours {
								display: flex;
								flex-direction: row;
								align-items: center;
								margin-bottom: 12rpx;
								width: 100%;

								.business_left {
									display: flex;
									flex-direction: row;
									align-items: center;
									flex: 1;
								}

								.official {
									font-size: 24rpx;
									font-weight: 500;
									// color: #81cac5;
								}

								.concrete_time {
									margin: 0 8rpx;
									font-size: 24rpx;
									font-weight: 400;
									color: #999999;
								}

								.size1 {
									font-size: 24rpx;
									font-weight: 500;
									color: #666666;

								}

								.navigation {
									display: flex;
									flex-direction: row;
									align-items: center;

									.logo {
										width: 22rpx;
										height: 22rpx;
									}

									.size {
										font-size: 24rpx;
										font-weight: 500;
										color: #81cac5;
									}
								}
							}

							.address {
								font-size: 24rpx;
								font-family: PingFang SC, PingFang SC-Regular;
								font-weight: 400;
								text-align: left;
								color: #333333;
								display: -webkit-box;
								-webkit-line-clamp: 2;
								/* 限制显示的行数 */
								-webkit-box-orient: vertical;
								overflow: hidden;
								text-overflow: ellipsis;
								/* 显示省略号 */
								white-space: normal;
								/* 处理空白符 */
							}
						}
					}

					.foot_box {
						display: flex;
						flex-direction: row;
						align-items: center;
						justify-content: space-around;
						width: 100%;

						.btn1 {
							width: 300rpx;
							height: 72rpx;
							border: 1rpx solid #81cac5;
							border-radius: 16rpx;
							font-size: 28rpx;
							font-family: PingFang SC, PingFang SC-Bold;
							font-weight: 700;
							color: #81cac5;
							display: flex;
							align-items: center;
							justify-content: center;
						}

						.btn2 {
							width: 300rpx;
							height: 72rpx;
							background: #81cac5;
							border-radius: 16rpx;
							font-size: 28rpx;
							font-family: PingFang SC, PingFang SC-Bold;
							font-weight: 700;
							color: #ffffff;
							display: flex;
							align-items: center;
							justify-content: center;
						}
					}
				}
			}
		}
	}
</style>